from flask import Blueprint, render_template, \
    current_app, request, flash, redirect, url_for, jsonify
from flask_login import login_required
from app.models.article import Article
from app.models.category import Category
from app.models.user import User
from app.forms.article import ArticleForm
from app.forms.common import AjaxDeleteForm, FileUploadForm
from datetime import datetime
from flask_ckeditor import upload_success, upload_fail
from app.extensions import db
from uuid import uuid4
from flask_login import current_user
from app.helpers import oss_bucket
import json

bp = Blueprint('article', __name__)


@bp.before_request
@login_required
def before_request():
    """before_request的生命周期加入了login_required装饰
    """
    pass


@bp.context_processor
def make_template_context():
    return dict(category=Category.query.all())


@bp.route('/')
def index():
    """文章列表页
    """
    page = request.args.get('page', 1, type=int)
    cid = request.args.get('cid', None, type=int)

    query = Article.query.order_by(
        Article.id.desc()).filter(Article.status == 9)
    if cid:
        query = query.filter(Article.cid == cid)

    pre_page = current_app.config['POST_PRE_PAGE']
    pagination = query.paginate(page, pre_page)
    return render_template('admin/article/index.html',
                           model=pagination.items,
                           page=page,
                           pagination=pagination)


@bp.route('/create', methods=['GET', 'POST'])
def create():
    """文章创建
    """
    form = ArticleForm()
    cid = request.args.get('cid', type=int)
    model = Article()
    if model.save(form, uid=current_user.id):
        flash('添加文章成功', 'success')
        return redirect(url_for('article.index', cid=cid))
    form.cid.data = cid

    return render_template('admin/article/create.html', form=form)


@bp.route('/update/<int:id>', methods=['GET', 'POST'])
def update(id):
    """文章更新
    """
    form = ArticleForm()
    model = Article.query.get_or_404(id)

    if model.save(form):
        flash('更新成功', 'success')
        return redirect(url_for('article.index', cid=model.cid))

    form.load(model)

    return render_template('admin/article/update.html', form=form, model=model)


@bp.route('/view/<int:id>', methods=['GET'])
def view(id):
    """文章查看页
    """
    model = Article.query.get_or_404(id)
    return render_template('admin/article/view.html', model=model)


@bp.route('/delete/<int:id>')
def delete(id):
    """单个删除
    """
    physics = request.args.get('physics', type=int)
    Article.query.get_or_404(id).delete(True if physics == 1 else False)
    flash('删除成功', 'success')
    return redirect(request.referrer or url_for('article.index'))


@bp.route('/ajax_delete', methods=['POST'])
def ajax_delete():
    """批量删除
    """
    form = AjaxDeleteForm()
    physics = request.args.get('physics', type=int)
    if form.validate_on_submit():
        for i in json.loads(form.ids.data):
            Article.query.get_or_404(i).delete(True if physics == 1 else False)
        flash('删除成功', 'success')

    if form.errors:
        flash(form.errors, 'danger')

    return jsonify({'success': True, 'message': '删除成功'})


@bp.route('/trash')
def trash():
    """回收站
    """
    page = request.args.get('page', 1, type=int)
    query = Article.query.filter_by(status=0).order_by(Article.id.desc())
    pre_page = current_app.config['POST_PRE_PAGE']
    pagination = query.paginate(page, pre_page)
    category = Category.query.all()
    return render_template('admin/article/trash.html',
                           model=pagination.items,
                           page=page,
                           pagination=pagination,
                           category=category)


@bp.route('/ajax_restore', methods=['POST'])
def ajax_restore():
    """批量还原
    """
    form = AjaxDeleteForm()
    if form.validate_on_submit():
        for i in json.loads(form.ids.data):
            Article.query.get_or_404(i).status = 9
        flash('还原成功', 'success')
        db.session.commit()

    if form.errors:
        flash(form.errors, 'danger')

    return jsonify({'success': True, 'message': '还原成功'})


@bp.route('/upload', methods=['POST'])
def upload_image():
    """缩略图上传
    """
    fileForm = FileUploadForm()
    if fileForm.validate_on_submit():
        file = request.files.get('upload')
        extension = file.filename.split('.')[1].lower()
        filename = '/'.join([
            datetime.now().strftime('%Y-%m-%d'),
            '{}.{}'.format(uuid4(), extension)
        ])
        oss_bucket.put_object(filename, file.read())
        url = 'https://lsol-house-upload.oss-cn-hangzhou.aliyuncs.com/{}'.format(
            filename)
        return upload_success(url=url)

    return upload_fail(message=fileForm.errors['upload'])
